import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'


//axios全局引入
import axios from "axios"
axios.defaults.baseURL="/api"
Vue.prototype.$http=axios


import routes from './routes'
//原始的数据是从mock.js中模拟的数据 -> 要从后端获取数据 -，所以要注释掉


import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})

/*axios前置拦截器  作用：只要发送axios请求之前，它就会执行此函数*/
axios.interceptors.request.use(config => {
    //携带token
    let token = localStorage.getItem("token");
    if (token) {
        //如果token有值，我就添加请求头信息  TOKEN
        config.headers['TOKEN'] = token;
    }
    return config;
}, error => {
    Promise.reject(error);
});


//axios的后置拦截器，在响应目标方法之前，先执行此箭头函数
axios.interceptors.response.use(result => {
    let {success, msg} = result.data;
    if (!success && msg === "NoLogin") {
        //清空token和loginUser
        localStorage.removeItem("token");
        localStorage.removeItem("loginUser");
        alert(localStorage.getItem("loginUser"));
        //跳转到登录界面
        router.push({path: '/login'});

    }

    return result;
}, error => {
    Promise.reject(error);
});
//登录拦截的代码 - 只要登录成功之后才能进入
router.beforeEach((to, from, next) => {
    if(to.path=="/login"||to.path=="/shopReg"){
        //放行
        next();
    }else{
        //获取token的值
        var token = localStorage.getItem("token");
        //如果token有值，就证明是登录状态，应该直接放行
        if(token){
            next();
        }else{
            localStorage.removeItem("token");
            localStorage.removeItem("loginUser");
            //否则跳转到登录界面
            next({ path: '/login' })
        }
    }
})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

